package com.hns.can.upgrade.web;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hns.can.base.entity.SysCorpInfoEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.web.BaseController;
import com.hns.can.master.entity.BaseCarInfoEntity;
import com.hns.can.master.entity.BaseEqmtInfoEntity;
import com.hns.can.master.entity.BaseLineInfoEntity;
import com.hns.can.upgrade.entity.UpgEqmtIssuedParamTemp;
import com.hns.can.upgrade.entity.UpgEqmtVrsnManageInfo;
import com.hns.can.upgrade.entity.UpgEqmtVrsnParamDetail;
import com.hns.can.upgrade.enumrate.UpgradeVersionTypeEnum;
import com.hns.can.upgrade.service.UpgradeFileSetService;
import com.hns.can.upgrade.vo.UpgEqmtIssuedParamVo;
import com.hns.can.upgrade.vo.UpgradeVo;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.tool.pub.FTPUtils;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilConfig;

/**
 * 升级控制类
 * @author:lan
 * @email:763836737@qq.com
 * @version Revision 2.0.0
 */
@Controller
@RequestMapping("/upgrade")
public class UpgradeFileSetControllor extends BaseController {

    /**
     * 升级文件设置service
     */
	@Autowired
    private UpgradeFileSetService upgradeFileSetService;

    /**
     * 查询升级文件设置
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/getFileSetPage")
    @ResponseBody
    public Object getFileSetPage(UpgradeVo vo) throws Exception {
        Pagination page = upgradeFileSetService.getFileSetPage(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }


    /**
     * 查询升级命令设置
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/getByFilePage")
    @ResponseBody
    public Object getByFilePage(UpgradeVo vo) throws Exception {
        Pagination page = upgradeFileSetService.getByFilePage(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }

    /**
     * @param upgFile
     * @param entity
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-22
     * @功能说明：添加应用
     */
    @RequestMapping("/addAppMgr")
    @ResponseBody
    public Object addAppMgr(@RequestParam(value = "upgFile", required = true) MultipartFile upgFile,
                            UpgEqmtVrsnManageInfo entity) throws Exception {
        /*根据应用升级项生成ftp目录*/
        //文件名、后缀名和原文件一致
        String oldFileName = upgFile.getOriginalFilename();
        //判断文件名是否包含中文和空格
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(oldFileName);
        if (m.find() || oldFileName.indexOf(" ") > 0) {
            throw new BusinessException(MsgType.WARN.getFlag(), "您上传的文件名中有空格或文件名中包含中文！");
        }
        String addPath = "";
        if(UpgradeVersionTypeEnum.CORE_BOARD.getFlag().equals(entity.getAppUpgrade())){ // 核心板应用
            addPath = UtilConfig.getString("ftp_update_center_coreboard")+entity.getVrsnName()+"/";
            FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), addPath);
        }else if(UpgradeVersionTypeEnum.MAIN_BOARD.getFlag().equals(entity.getAppUpgrade())){
            addPath = UtilConfig.getString("ftp_update_center_mainboard")+entity.getVrsnName()+"/";
            FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), addPath);
        }else if(UpgradeVersionTypeEnum.CAR_CANUPGVS.getFlag().equals(entity.getVrsnType())){
            addPath = UtilConfig.getString("ftp_update_center_canconfig")+entity.getVrsnName()+"/";
            FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), addPath);
        }
        entity.setFtpUpgradeAdr(oldFileName);
        if(PubUtil.isNotEmpty(entity.getAppUpgrade())){
            switch (entity.getAppUpgrade()) {
                case "APUP0001": entity.setVrsnType("VERS0001");
                    break;
                case "APUP0002": entity.setVrsnType("VERS0001");
                    break;
                case "APUP0003": entity.setVrsnType("VERS0001");
                    break;
            }
        }
        try {
            /*保存到ftp*/
            FTPUtils.ftpUpload(upgFile.getInputStream(), addPath, oldFileName);
            /*保存数据库*/
            upgradeFileSetService.addAppMgr(entity);
        } catch (Exception e) {
//            logger.error("上传有误！"+e.getMessage(),e);
            throw new BusinessException(MsgType.ERROR.getFlag(), "上传有误！"+e.getMessage());
        }

        return this.getReturnMsg("您成功添加一个应用");
    }

    /**
     * 获取车辆型号
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/getCarModel")
    @ResponseBody
    public Object getCarModel() throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        String corpId = user.getCorpId();
        BaseCarInfoEntity entity = new BaseCarInfoEntity();
        entity.setCorpId(corpId);
        List<BaseCarInfoEntity> list = upgradeFileSetService.getCarModel(entity);
        return this.getReturnResult(list);
    }

    /**
     * @param upgFile
     * @param entity
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-29
     * @功能说明：添加一个线路文件
     */
    @RequestMapping("/addLineMgr")
    @ResponseBody
    public Object addLineMgr(@RequestParam(value = "upgFile", required = true) MultipartFile upgFile,
                           UpgEqmtVrsnManageInfo entity) throws Exception {
        String oldFileName = upgFile.getOriginalFilename();//文件名后缀不变
        //判断文件名是否包含中文和空格
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(oldFileName);
        if (m.find() || oldFileName.indexOf(" ") > 0) {
            throw new BusinessException(MsgType.WARN.getFlag(), "您上传的文件名中有空格或文件名中包含中文！");
        }
        SysUserEntity user = this.getCurrentUser().getUser();
        String corpId = user.getCorpId();
        SysCorpInfoEntity corp = upgradeFileSetService.getSysCorpInfoByCorpId(corpId);
        BaseLineInfoEntity line = upgradeFileSetService.getBaseLineInfoByLineId(entity.getLineId());
        String addPath = UtilConfig.getString("ftp_update_center_lineconfig")+corp.getCorpEngAb()+"/"+line.getLineCode()+"/"+entity.getVrsnName()+"/";
        //先保存数据库
//        String oldFileName = upgFile.getOriginalFilename(); //文件名后缀不变
        entity.setFtpUpgradeAdr(oldFileName);
        upgradeFileSetService.addLineMgr(entity);
        //再保存到ftp
        FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), addPath);
        FTPUtils.ftpUpload(upgFile.getInputStream(), addPath, oldFileName);
        return this.getReturnMsg("您成功添加一个线路文件");
    }

    /**
     *
     * @param vo
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-10-23
     * @功能说明： 命令升级
     */
    @RequestMapping("/addCanMgr")
    @ResponseBody
    public Object addCanMgr(UpgradeVo vo) throws Exception {
        List<BaseEqmtInfoEntity> list = upgradeFileSetService.saveLog(vo);
        upgradeFileSetService.addCanMgr(vo,list);
        return this.getReturnResult("");
        //直接跳转远程命令升级，不做提示
        //return this.getReturnMsg("您成功添加一个通讯参数文件");
    }

    /**
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-29
     * @功能说明：添加一个外设文件
     */
    @RequestMapping("/addPerMgr")
    @ResponseBody
    public Object addPerMgr( UpgradeVo vo) throws Exception {
        upgradeFileSetService.addPerMgr(vo);
        return this.getReturnMsg("您成功添加一个外设文件");
    }

    /**
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-29
     * @功能说明：添加一个状态文件
     */
    @RequestMapping("/addStatusMgr")
    @ResponseBody
    public Object  addStatusMgr(UpgradeVo vo) throws Exception {
        upgradeFileSetService.addStatusMgr(vo);
        return this.getReturnMsg("您成功添加个状态文件");
    }

    /**
     * 删除各种类型
     * @param vrsnId
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/delUpgrade")
    @ResponseBody
    public Object delUpgrade(UpgradeVo vo) throws Exception {
        upgradeFileSetService.delUpgrade(vo);
        return this.getReturnMsg("删除成功");
    }

    /**
     * @throws Exceptions
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-29
     * @功能说明：添加一个状态文件
     */
    @RequestMapping("/addUpgradeFile")
    @ResponseBody
    public Object  addUpgradeFile(UpgradeVo vo) throws Exception {
        upgradeFileSetService.addUpgradeFile(vo);
        return this.getReturnMsg("您成功添加个状态文件");
    }

    /**
     * @throws Exceptions
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-29
     * @功能说明：查询升级命令
     */
    @RequestMapping("/getDetailByVrsnId")
    @ResponseBody
    public Object getDetailByVrsnId(String vrsnId) throws Exception {
        List<UpgEqmtVrsnParamDetail> list = upgradeFileSetService.getDetailByVrsnId(vrsnId);
        return this.getReturnResult(list);
    }

    /**
     * @author:JeffXu
     * @throws Exception
     * @email:835264047@qq.com
     * @创建日期:2014-9-19
     * @功能说明：获取设备参数信息
     */
    @RequestMapping("/getParamByVrsnType")
    @ResponseBody
    public Object getParamByVrsnType(String vrsnType) throws Exception {
        List<UpgEqmtIssuedParamTemp> list = upgradeFileSetService.getParamByVrsnType(vrsnType);
        return this.getReturnResult(list);
    }

    /**
     * 获取设备下发参数模板
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/getIssuedParam")
    @ResponseBody
    public Object getIssuedParam(String paramIssue) throws Exception {
        List<UpgEqmtIssuedParamVo> list = upgradeFileSetService.getIssuedParam(paramIssue);
        return this.getReturnResult(list);
    }

    /**
     * 查询命令升级日志
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/searchLogPage")
    @ResponseBody
    public Object searchLogPage(UpgradeVo vo) throws Exception {
        Pagination page = upgradeFileSetService.searchLogPage(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }

    /**
     *
     * @param vo
     * @param request
     * @param response
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-23
     * @功能说明： 查询文件升级
     */
    @RequestMapping("/searchUpgrade")
    @ResponseBody
    public Object searchUpgrade(UpgradeVo vo)throws Exception{
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        Pagination page =  upgradeFileSetService.searchUpgrade(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }

    /**
     *
     * @param request
     * @param respons
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-22
     * @功能说明：获取升级版本名称
     */
    @RequestMapping("/getVersionName")
    @ResponseBody
    public Object getVersionName(UpgradeVo  vo)throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        List<UpgEqmtVrsnManageInfo> list = upgradeFileSetService.getVersionName(vo);
        return this.getReturnResult(list);
    }

    /**
     *
     * @param request
     * @param respons
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-22
     * @功能说明：文件升级
     */
    @RequestMapping("/softwareUpgrade")
    @ResponseBody
    public Object softwareUpgrade(UpgradeVo vo)throws Exception {
        upgradeFileSetService.softwareUpgrade(vo);
        return this.getReturnMsg(null);
    }

    /**
     *
     * @param request
     * @param respons
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-22
     * @功能说明：设备文件下载  查询
     */
    @RequestMapping("/searchDevLogUploadPage")
    @ResponseBody
    public Object searchDevLogUploadPage(UpgradeVo vo) throws Exception {
        Pagination page = upgradeFileSetService.searchDevLogUploadPage(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }

    /**
     *
     * @param request
     * @param respons
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-22
     * @功能说明：设备文件下载  上传
     */
    @RequestMapping("/devLogUpload")
    @ResponseBody
    public Object devLogUpload(UpgradeVo vo)throws Exception{
        SysUserEntity user = this.getCurrentUser().getUser();
        upgradeFileSetService.devLogUpload(vo);
        return this.getReturnMsg(null);
    }

    /**
     *
     * @param vo
     * @param request
     * @param response
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-23
     * @功能说明： 查询文件升级
     */
    @RequestMapping("/searchUpgradeLog")
    @ResponseBody
    public Object searchUpgradeLog(UpgradeVo vo)throws Exception{
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        Pagination page =  upgradeFileSetService.searchUpgradeLog(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
}